package com.android.view.hqview;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.LayerDrawable;
import android.graphics.drawable.StateListDrawable;
import android.os.Handler;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.android.R;

import java.util.ArrayList;


public class TabScrollButton extends HorizontalScrollView implements View.OnClickListener {

    public OnCheckedChangeListener onCheckedChangeListener = new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(int position, RelativeLayout textview) {

        }
    };

    public void setOnCheckedChangeListener(
            OnCheckedChangeListener onCheckedChangeListener) {
        this.onCheckedChangeListener = onCheckedChangeListener;
    }

    private Context context;
    private ArrayList<RelativeLayout> relativelayoutList;
    private int height;
    private int width;
    public int maxbuttonCount = 3;


    public boolean isShouldCenter() {
        return shouldCenter;
    }

    public void setShouldCenter(boolean shouldCenter) {
        this.shouldCenter = shouldCenter;
    }

    private boolean shouldCenter;

    public void setContentStr(String[] str) {
        contentStr.clear();
        for (int i = 0; i < str.length; i++) {
            TabButtonItem item = new TabButtonItem();
            item.title = str[i];
            contentStr.add(item);
        }
    }

    public void setContentArray(ArrayList<TabButtonItem> contentStr) {
        this.contentStr = contentStr;
    }

    private ArrayList<TabButtonItem> contentStr;

    public void setPosition(int position, boolean shouldAnim) {
        this.position = position;
        changeSegment(position, shouldAnim);
    }

    public void setPosition(int position) {
        this.position = position;
        changeSegment(position, true);
    }

    private int position = 0;

    public float getTextSize() {
        return textSize;
    }

    public void setTextSize(float textSize) {
        this.textSize = textSize;
    }

    public int getTextPressColor() {
        return textPressColor;
    }

    public void setTextPressColor(int textPressColor) {
        this.textPressColor = textPressColor;
    }

    public int getTextNormalColor() {
        return textNormalColor;
    }

    public void setTextNormalColor(int textNormalColor) {
        this.textNormalColor = textNormalColor;
    }

    public int getStrokeColor() {
        return strokeColor;
    }

    public void setStrokeColor(int strokeColor) {
        this.strokeColor = strokeColor;
    }

    public int getNormalFillColor() {
        return normalFillColor;
    }

    public void setNormalFillColor(int normalFillColor) {
        this.normalFillColor = normalFillColor;
    }

    public int getPressFillColor() {
        return pressFillColor;
    }

    public void setPressFillColor(int pressFillColor) {
        this.pressFillColor = pressFillColor;
    }

    public int getStrokeWidth() {
        return strokeWidth;
    }

    public void setStrokeWidth(int strokeWidth) {
        this.strokeWidth = strokeWidth;
    }

    private int textPressColor;
    private int textNormalColor;
    private int strokeColor;
    private int normalFillColor;
    private int pressFillColor;
    private int strokeWidth;
    private float textSize;

    public float getButtonWidth() {
        return buttonWidth;
    }

    public void setButtonWidth(float buttonWidth) {
        this.buttonWidth = buttonWidth;
    }

    private float buttonWidth;

    public TabScrollButton(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
        this.context = context;
    }

    public void refresh() {
        setView();
    }

    public TabScrollButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
        this.context = context;
        TypedArray typedArray = context.obtainStyledAttributes(attrs,
                R.styleable.SegmentButton);
        textPressColor = typedArray.getColor(
                R.styleable.SegmentButton_textPressColor, Color.WHITE);
        textNormalColor = typedArray.getColor(
                R.styleable.SegmentButton_textNormalColor,
                Color.GRAY);
        strokeColor = typedArray.getColor(
                R.styleable.SegmentButton_allstrokeColor,
                Color.TRANSPARENT);
        normalFillColor = typedArray.getColor(
                R.styleable.SegmentButton_normalFillColor,
                Color.TRANSPARENT);
        pressFillColor = typedArray.getColor(
                R.styleable.SegmentButton_pressFillColor,
                Color.TRANSPARENT);
        textSize = 14f;
        strokeWidth = (int) convertDpToPixel(1f);
//       buttonWidth = convertDpToPixel(100);
        setHorizontalScrollBarEnabled(false);
        String buttonContent = typedArray
                .getString(R.styleable.SegmentButton_buttonContent);
        contentStr = new ArrayList<>();
        if (buttonContent != null && (!"".equals(buttonContent))) {
            String[] strs = buttonContent.split(";");
            for (int i = 0; i < strs.length; i++) {
                TabButtonItem it = new TabButtonItem();
                it.title = strs[i];
                contentStr.add(it);
            }
        }
        typedArray.recycle();
    }

    /**
     * location  0-左边，1-中间，2-右边
     * state 0-normal,1-selected
     */
    private Drawable getDrawable(int state) {
        GradientDrawable drawable = new GradientDrawable();
        drawable.setStroke(strokeWidth, strokeColor);
        LayerDrawable layerDrawable = new LayerDrawable(new Drawable[]{drawable});
        switch (state) {
            case 0:
                drawable.setColor(normalFillColor);
                layerDrawable.setLayerInset(0, -strokeWidth * 2, -strokeWidth * 2, -strokeWidth * 2, -strokeWidth * 2);
                break;
            case 1:
                drawable.setColor(pressFillColor);
                layerDrawable.setLayerInset(0, -strokeWidth * 2, -strokeWidth * 2, -strokeWidth * 2, strokeWidth * 2);
                break;
            default:
                break;
        }
        return layerDrawable;
    }

    private Drawable getSelector() {
        StateListDrawable stateListDrawable = new StateListDrawable();
        stateListDrawable.addState(new int[]{android.R.attr.state_selected}, getDrawable(1));
        stateListDrawable.addState(new int[]{}, getDrawable(0));
        return stateListDrawable;
    }

    private float convertDpToPixel(float dp) {
        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        float px = dp * (metrics.densityDpi / 160f);
        return px;
    }

    private void setView() {
        if (contentStr == null || contentStr.size() == 0)
            return;
        LinearLayout parent = new LinearLayout(context);
        RelativeLayout.LayoutParams rl;
        parent.setOrientation(LinearLayout.HORIZONTAL);
        LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
        parent.setLayoutParams(params);
        this.removeAllViews();
        if (relativelayoutList == null) {
            relativelayoutList = new ArrayList<RelativeLayout>();
        } else {
            relativelayoutList.clear();
        }

        int count = contentStr.size();
        for (int i = 0; i < count; i++) {

            RelativeLayout relativeLayout = new RelativeLayout(context);
            TextView textview = new TextView(context);
            textview.setBackgroundDrawable(getSelector());
            textview.setTextSize(TypedValue.COMPLEX_UNIT_DIP, textSize);
            textview.setText(contentStr.get(i).title);
            if (i == position) {
                textview.setSelected(true);
                textview.setTextColor(textPressColor);
//                textview.setTextSize(TypedValue.COMPLEX_UNIT_DIP, textSize + 3);
            } else {
                textview.setSelected(false);
                textview.setTextColor(textNormalColor);
//                textview.setTextSize(TypedValue.COMPLEX_UNIT_DIP, textSize);
            }
            if (contentStr.size() > maxbuttonCount) {
                int textwidth = calcuLength(textview.getText().toString(), textview);
                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams((int) (textwidth + convertDpToPixel(70)),
                        LayoutParams.MATCH_PARENT);
                relativeLayout.setLayoutParams(lp);
                textview.setGravity(Gravity.CENTER);
                textview.setPadding((int) convertDpToPixel(10), (int) convertDpToPixel(3), (int) convertDpToPixel(10), (int) convertDpToPixel(3));
                rl = new RelativeLayout.LayoutParams((int) (textwidth + convertDpToPixel(60)),
                        LayoutParams.MATCH_PARENT);
                rl.addRule(RelativeLayout.CENTER_IN_PARENT);
                textview.setLayoutParams(rl);
                relativeLayout.addView(textview);
                if (contentStr.get(i).itemType == 1) {
                    rl = new RelativeLayout.LayoutParams((int) convertDpToPixel(20), (int) convertDpToPixel(20));
                    rl.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                    rl.addRule(RelativeLayout.ALIGN_PARENT_TOP);
                    rl.setMargins((int) convertDpToPixel(10), (int) convertDpToPixel(3), (int) convertDpToPixel(10), (int) convertDpToPixel(3));
                    TextView tv = new TextView(context);
                    tv.setLayoutParams(rl);
                    tv.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.mine_setting));
                    tv.setTextColor(context.getResources().getColor(R.color.white));
                    tv.setGravity(Gravity.CENTER);
                    relativeLayout.addView(tv);
                }
            } else {
                buttonWidth = width / contentStr.size();
                int textwidth = calcuLength(textview.getText().toString(), textview);
                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams((int) (buttonWidth),
                        LayoutParams.MATCH_PARENT);
                relativeLayout.setLayoutParams(lp);
                textview.setGravity(Gravity.CENTER);
                textview.setPadding(0, 0, 0, 0);
                rl = new RelativeLayout.LayoutParams((int) (textwidth + convertDpToPixel(16)),
                        LayoutParams.MATCH_PARENT);
                rl.addRule(RelativeLayout.CENTER_IN_PARENT);
                textview.setLayoutParams(rl);
                relativeLayout.addView(textview);
                if (contentStr.get(i).itemType == 1) {
                    int padding = (int) ((buttonWidth - textwidth) / 2 - convertDpToPixel(9));
                    rl = new RelativeLayout.LayoutParams((int) convertDpToPixel(9), (int) convertDpToPixel(9));
                    rl.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                    rl.addRule(RelativeLayout.ALIGN_PARENT_TOP);
                    rl.setMargins(0, (int) convertDpToPixel(3), padding, 0);
                    TextView tv = new TextView(context);
                    tv.setLayoutParams(rl);
                    tv.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.mine_setting));
                    tv.setTextColor(context.getResources().getColor(R.color.white));
                    tv.setGravity(Gravity.CENTER);
                    relativeLayout.addView(tv);
                }
            }
            relativeLayout.setTag(i);
            parent.addView(relativeLayout);
            relativeLayout.setOnClickListener(this);
            relativelayoutList.add(relativeLayout);
        }
        addView(parent);
        if (shouldCenter) {
            toCenter(position);
        }
    }

    public int getPosition() {
        return position;
    }

    private int calcuLength(String str, TextView btn) {
        Rect bounds = new Rect();
        TextPaint paint;
        paint = btn.getPaint();
        paint.getTextBounds(str, 0, str.length(), bounds);
        return bounds.width();
    }
    public void perFormClick(int position) {
        relativelayoutList.get(position).performClick();
    }
    @Override
    public void onClick(View v) {
        if (isClick) {
            int i = (Integer) v.getTag();
            changeSegment(i, true);
            onCheckedChangeListener.onCheckedChanged(i,
                    (RelativeLayout) v);
        }

    }
    private boolean isClick = true;
    public void setIsClick(boolean isClick) {
        this.isClick = isClick;
    }


    private void changeSegment(final int index, final boolean shouldAnim) {
        if (relativelayoutList == null || relativelayoutList.size() == 0)
            return;
        for (int i = 0; i < contentStr.size(); i++) {
            if (index == i) {
                relativelayoutList.get(i).getChildAt(0).setSelected(true);
                ((TextView) (relativelayoutList.get(i).getChildAt(0))).setTextColor(textPressColor);
                position = i;
            } else {
                relativelayoutList.get(i).getChildAt(0).setSelected(false);
                ((TextView) (relativelayoutList.get(i).getChildAt(0))).setTextColor(textNormalColor);
            }
        }
        if (buttonWidth == 0) {
            if (shouldCenter) {
                srcollToCenter(index);
            } else {
                int right = relativelayoutList.get(index).getRight();
                if (right == 0) {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            changeSegment(index, shouldAnim);
                        }
                    }, 50);
                }
                int offset = right - getScrollX();
                if (offset > width) {
                    offset = right - width;
                    scrollAnim(offset, shouldAnim);
                }
                int left = relativelayoutList.get(index).getLeft();
                offset = getScrollX() - left;
                if (offset > 0) {
                    offset = getScrollX() - offset;
                    scrollAnim(offset, shouldAnim);
                }
            }
        }
    }

    private void srcollToCenter(int index) {
        int right = relativelayoutList.get(index).getRight();
        int layoutwidth = relativelayoutList.get(index).getWidth();
        layoutwidth = (width + layoutwidth) / 2;
        scrollAnim(right - layoutwidth);
    }

    private void toCenter(final int index) {
        if (width == 0) {
            return;
        }
        int right = relativelayoutList.get(index).getRight();
        int layoutwidth = relativelayoutList.get(index).getWidth();
        if (layoutwidth == 0) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    toCenter(index);
                }
            }, 50);
        } else {
            layoutwidth = (width + layoutwidth) / 2;
            scrollAnim(right - layoutwidth, false);
        }
    }

    private void scrollAnim(int offset, boolean showanim) {
        if (android.os.Build.VERSION.SDK_INT < 11) {
            if (showanim) {
                smoothScrollTo(offset, 0);
            } else {
                scrollTo(offset, 0);
            }
        } else {
            if (showanim) {
                ObjectAnimator in = ObjectAnimator.ofInt(this, "scrollX", offset);
                in.setDuration(300);
                in.start();
            } else {
                scrollTo(offset, 0);
            }
        }
    }

    private void scrollAnim(int offset) {
        scrollAnim(offset, true);
    }

    public RelativeLayout getSegmentButton(int position) {
        return relativelayoutList.get(position);
    }

    public interface OnCheckedChangeListener {
        public void onCheckedChanged(int position, RelativeLayout V);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        width = MeasureSpec.getSize(widthMeasureSpec);
        height = MeasureSpec.getSize(heightMeasureSpec);
        if (!first) {
            setView();
            first = true;
        }
    }

    private boolean first;

}
